/*
 * Copyright (c) 2020-2021, SERI Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-11-14     Lyons        first version
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define CURRENT_VERSION             "v1.1.0"

#define ERR_EOK                     0
#define ERR_ERROR                   1

typedef unsigned long       uint32_t;
typedef long                int32_t;
typedef unsigned short      uint16_t;
typedef short               int16_t;
typedef unsigned char       uint8_t;
typedef char                int8_t;

static uint32_t _code_size;
static uint8_t _code_buffer[256*1024]; //256KByte

int main( int argc,char **argv )
{
    FILE *fsrc;
    FILE *fdst;

    const char *src = argv[1];
    const char *dst = argv[2];

    system("@chcp 936 >NUL");
    system("@title bin2mem " CURRENT_VERSION " chcp=936");

    fsrc = fopen(src, "rb");
    fdst = fopen(dst, "w");

    _code_size = fread(_code_buffer, sizeof(uint8_t), sizeof(_code_buffer), fsrc);

    fprintf(fdst, "memory_initialization_radix = 16;\n");
    fprintf(fdst, "memory_initialization_vector = \n");

    for (uint32_t i=0; i<_code_size; i+=4)
    {
        uint32_t data = (_code_buffer[i+3] << 24)
                      | (_code_buffer[i+2] << 16)
                      | (_code_buffer[i+1] << 8)
                      | (_code_buffer[i+0] << 0);

        if ((i + 4) >= _code_size)
        {
            fprintf(fdst, "%08x;\n", data);
        } else {
            fprintf(fdst, "%08x,\n", data);
        }
    }

    fclose(fsrc);
    fclose(fdst);

    return ERR_EOK;
}